import 'dart:io';

import 'package:aichat_flutter_wallet/module/module_create_wallet/widgets/password.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/agreement/agreement_comp.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/header/page_header.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/public_tip/validate_tip.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lib_database/lib_database.dart';
import 'package:lib_language/lib_language.dart';
import 'package:lib_util/lib_util.dart';
import 'package:lib_util/utils/utils.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/dialog/password_auth_dialog.dart';
import 'package:lib_database/src/network.dart';
import '../../../module_common/bridge/native_channel_bridge.dart';
import '../../../module_common/mpc_help/createWalletTool.dart';
import '../../../module_common/provider/user_settings_provider.dart';
import '../../../module_common/provider/wallet_info_provider.dart';
import '../../../module_common/router/routers.dart';
import '../../../module_common/utils/auth.dart';
import '../../../module_common/widgets/button/public_button.dart';
import '../../../module_common/widgets/dialog/easyloading.dart';
import '../../../module_common/widgets/image/public_image.dart';
import '../../../module_common/widgets/public_tip/public_tip.dart';
import '../utils/create_or_import.dart';

class SetPassPage extends StatefulWidget {
  // 1 创建钱包， 2 导入钱包， 3 修改密码
  final String type;
  final String? privateKey;

  SetPassPage({super.key, this.type = '1', this.privateKey = ''});

  @override
  State<SetPassPage> createState() => _SetPassPageState();
}

class _SetPassPageState extends State<SetPassPage> {
  TextEditingController _textEditingController = TextEditingController();
  FocusNode _focusNode = FocusNode();

  final bool isPasswordSet = false;
  bool biometricLogin = false;
  bool goingHome = false;
  String password1 = '';
  String password2 = '';
  bool showPassword1 = false;
  bool showPassword2 = false;
  String showPassword1Warn = '';
  String showPassword2Warn = '';
  String inputValue = 'Wallet1';
  bool isBiometric = false;
  bool isAgree = false;

  get privateKey => widget.privateKey;

  TextEditingController textEditingController = TextEditingController();

  Map<String, dynamic> get textMap {
    Map<String, dynamic> myMap = {};
    myMap['input_label'] = 'Wallet Name';
    if (widget.type == '1') {
      myMap['page_title'] = '';
      myMap['title'] = 'Create Wallet Password';
      myMap['needAgreement'] = true;
      myMap['sub_title'] =
          'This password will only be used to unlock KAI in this device, and the password will only be saved in this device.';
      myMap['btn_text'] = 'Confirm Create';
      myMap['input_1_label'] = 'Set Password';
      myMap['placeholder_1_label'] = 'Minimum 8 characters';
      myMap['input_2_label'] = 'Confirm Password';
      myMap['placeholder_2_label'] = 'Confirm Password';
      myMap['show_Biometric'] = false;
      myMap['show_Biometric_text'] = '';
    } else if (widget.type == '2') {
      myMap['page_title'] = '';
      myMap['title'] = 'Import Wallet Password';
      myMap['needAgreement'] = true;
      myMap['sub_title'] =
          'This password will only be used to unlock KAl in this device,and the password will only be saved in this device.';
      myMap['input_1_label'] = 'Set Password';
      myMap['placeholder_1_label'] = 'Minimum 8 characters';
      myMap['input_2_label'] = 'Confirm Password';
      myMap['placeholder_2_label'] = 'Confirm Password';
      myMap['btn_text'] = 'Confirm Import';
      myMap['show_Biometric'] = false;
      myMap['show_Biometric_text'] = '';
    } else if (widget.type == '3') {
      myMap['page_title'] = 'Change wallet password';
      myMap['title'] = '';
      myMap['needAgreement'] = false;
      myMap['sub_title'] =
          'This password will only be used to unlock KAl in thisdevice,and the password will only be saved in this device.';
      myMap['input_1_label'] = 'New Wallet Password';
      myMap['placeholder_1_label'] = 'Please enter an 8-digit wallet password';
      myMap['input_2_label'] = 'Confirm Wallet Password';
      myMap['placeholder_2_label'] = 'Match your wallet password';
      myMap['btn_text'] = 'Confirm';
      myMap['show_Biometric'] = false;
      myMap['show_Biometric_text'] = '';
    } else if (widget.type == '4') {
      myMap['page_title'] = 'Set Wallet Password';
      myMap['title'] = '';
      myMap['needAgreement'] = false;
      myMap['sub_title'] = '';
      myMap['input_1_label'] = 'Wallet Password';
      myMap['placeholder_1_label'] = 'Please enter an 8-digit wallet password';
      myMap['input_2_label'] = 'Confirm wallet password';
      myMap['placeholder_2_label'] = 'Match your wallet password';
      myMap['btn_text'] = 'Confirm';
      myMap['show_Biometric'] = true;
      myMap['show_Biometric_text'] = 'Activate Biometric Authentication';
    }
    return myMap;
  }

  @override
  void initState() {
    super.initState();
    initStatus();
  }

  void initStatus() async {
    textEditingController.text = inputValue;
  }

  @override
  void dispose() {
    _focusNode.unfocus();
    _focusNode.dispose();
    _textEditingController.dispose();
    super.dispose();
  }

  _doConfirm() async {
    if (['1', '2', '4'].contains(widget.type) && inputValue.length <= 0) {
      Toast.show(context,
          status: '2',
          position: Dpositon.bottom,
          message: 'Please enter wallet name',
          duration: Duration(milliseconds: 2000));
      return;
    }
    if (showPassword2Warn.length > 0)
      setState(() {
        showPassword2Warn = '';
      });
    //未设置过密码，校验password1和password2
    if (Utils.isEmpty(password1)) {
      setState(() {
        showPassword1Warn = 'The password must contain at least 8 digits';
      });
      return;
    }
    if (Utils.isEmpty(password2)) {
      setState(() {
        showPassword2Warn = 'The password must contain at least 8 digits';
      });
    }
    if (password1 != password2) {
      setState(() {
        showPassword2Warn = 'Passwords do not match';
      });
      return;
    }
    if (['1', '2'].contains(widget.type) && !isAgree) {
      Toast.show(context,
          status: '2',
          position: Dpositon.bottom,
          message: 'Please read and agree to the agreement first!',
          duration: Duration(milliseconds: 2000));
      return;
    }
    // 创建
    if (widget.type == '1') {
      String key = WalletUtils().createMnemonic();
      // 校验 key ，返回 Key  以及 是否正确
      Map<String, dynamic> params = CreateOrImport.validateWallet(key);
      List<Chain> chains = ChainList().chains;
      final userId = NativeChannelBridge.instance.appCommMsg?.userId ?? '';
      Authentication()
          .updateObPassword(password1, context.read<UserSettingsProvider>());
      EasyLoading.generateLoadingFuture(
              createWalletTool().createWallet(
                  params['privateKey'], chains, userId,
                  walletName: inputValue),
              status: LocaleKeys.zhengzaichuangjianqianbao.tr())
          .then((value) {
        context.read<WalletInfoNotifier>().updateCurrentWallet(value[0]);
        Map<String, dynamic> routeParams = {};
        routeParams['wallet_id'] = value[0].id.toString();
        Routes.navigateTo(context, Routes.create_mnemonic,
            params: routeParams, clearStack: true);
      });
    } else if (widget.type == '2') {
      // 导入钱包
      if (privateKey.length <= 0) {
        Toast.show(context,
            status: '2',
            position: Dpositon.bottom,
            message: 'The private key is lost and does not exist',
            duration: Duration(milliseconds: 2000));
        return;
      }
      List<Chain>? chains = ChainList().chains;
      final userId = NativeChannelBridge.instance.appCommMsg?.userId ?? '';
      Authentication()
          .updateObPassword(password1, context.read<UserSettingsProvider>());
      EasyLoading.generateLoadingFuture(
              createWalletTool().createWallet(privateKey, chains, userId,
                  walletName: inputValue),
              status: LocaleKeys.zhengzaichuangjianqianbao.tr())
          .then((value) {
        context.read<WalletInfoNotifier>().updateCurrentWallet(value[0]);
        Navigator.pushNamedAndRemoveUntil(
          context,
          Routes.rootAssetsPage, // 要跳转的新路由名称
          (route) => false, // 移除所有路由记录
        );
      });
    } else if (widget.type == '3') {
      bool pass = await Authentication().startLocalAuth(
          showPasswordError: false,
          title: 'Please enter the old password for operation',
          callBackError: () {
            Toast.show(context,
                status: '0',
                position: Dpositon.top,
                message: "Verification password error",
                duration: Duration(milliseconds: 3000));
          });
      if (!pass) return;
      // 更新密码 后跳转
      Authentication()
          .updateObPassword(password1, context.read<UserSettingsProvider>());
      context.read<WalletInfoNotifier>();
      Navigator.of(context).pop();
    } else if (widget.type == '4') {
      Authentication().updateObPassword(
          password1, context.read<UserSettingsProvider>(),
          biometric: isBiometric);
      Navigator.of(context).pop();
    }
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
        appBar: PageHeaderCom(
          title: textMap['page_title'],
          showBottomBorder:
              widget.type == '4' ? false : textMap['page_title'].length > 0,
        ),
        // resizeToAvoidBottomInset: false,
        backgroundColor: Colors.white,
        body: SingleChildScrollView(
          child: Container(
            width: double.infinity,
            padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 10.w),
            child: Column(
              children: [
                if (textMap['title'].length > 0)
                  Align(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      textMap['title'],
                      style: TextStyle(
                          color: Color.fromRGBO(51, 51, 51, 1),
                          height: 22.w / 16.w,
                          fontSize: 16.sp,
                          fontWeight: FontWeight.w500),
                    ),
                  ),
                SizedBox(
                  height: 5.w,
                ),
                Visibility(
                    visible: textMap['sub_title'].length > 0,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: Text(
                        textMap['sub_title'],
                        style: TextStyle(
                            color: Color.fromRGBO(134, 131, 145, 1),
                            height: 16.w / 12.w,
                            fontSize: 12.sp,
                            fontWeight: FontWeight.w500),
                      ),
                    )),
                SizedBox(
                  height: textMap['show_Biometric'] == true ? 4.w : 30.w,
                ),
                Align(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    textMap['input_1_label'],
                    style: TextStyle(
                        color: Color.fromRGBO(0, 0, 0, 1),
                        height: 20.w / 14.w,
                        fontSize: 14.sp,
                        fontWeight: FontWeight.w500),
                  ),
                ),
                Container(
                  width: double.infinity,
                  padding: EdgeInsets.only(left: 15.w, right: 15.w),
                  height: 50.w,
                  margin: EdgeInsets.only(top: 10.w),
                  decoration: BoxDecoration(
                      color: Color.fromRGBO(246, 246, 246, 1),
                      borderRadius: BorderRadius.circular(10.w)),
                  child: Row(
                    children: [
                      Expanded(
                        child: GestureDetector(
                            behavior: HitTestBehavior.translucent,
                            onTap: () async {
                              dynamic result =
                                  await Utils.showBottomSheetDialog(
                                      context,
                                      PasswordAuthDialog(
                                        title: widget.type == '4'
                                            ? 'Please set wallet password'
                                            : 'Please set a new password',
                                      ));
                              if (null != result &&
                                  result is String &&
                                  Utils.isNotEmpty(result)) {
                                setState(() {
                                  password1 = result;
                                });
                              }
                            },
                            child: Utils.isEmpty(password1)
                                ? Text(
                                    textMap['placeholder_1_label'],
                                    style: TextStyle(
                                        height: 20.w / 14.w,
                                        fontWeight: FontWeight.w400,
                                        fontSize: 14.sp,
                                        color:
                                            Color.fromRGBO(190, 189, 202, 1)),
                                  )
                                : GeneratePassword.generatePasswordWidget(
                                    password1, showPassword1)),
                      ),
                      Visibility(
                        visible: true,
                        child: GestureDetector(
                            onTap: () {
                              setState(() {
                                showPassword1 = !showPassword1;
                              });
                            },
                            child: (showPassword1
                                ? PublicImage(
                                    image:
                                        'assets/images/create_wallet/show_pass.png',
                                    width: 20.w,
                                    height: 20.w,
                                  )
                                : PublicImage(
                                    image:
                                        'assets/images/create_wallet/hide_pass.png',
                                    width: 20.w,
                                    height: 20.w,
                                  ))),
                      )
                    ],
                  ),
                ),
                if (showPassword1Warn.length > 0)
                  SizedBox(
                    height: 10.w,
                  ),
                Visibility(
                    visible: showPassword1Warn.length > 0,
                    child: ValidateTip(
                        text: 'The password must contain at least 8 digits',
                        margin: EdgeInsets.zero,
                        onClose: () {
                          setState(() {
                            showPassword1Warn = '';
                          });
                        })),
                Align(
                  alignment: Alignment.centerLeft,
                  child: Padding(
                    padding: EdgeInsets.only(top: 20.w),
                    child: Text(
                      textMap['input_2_label'],
                      style: TextStyle(
                          color: Color.fromRGBO(51, 51, 51, 1),
                          height: 20.w / 14.w,
                          fontSize: 14.sp,
                          fontWeight: FontWeight.w500),
                    ),
                  ),
                ),
                Container(
                  width: double.infinity,
                  padding: EdgeInsets.only(left: 15.w, right: 15.w),
                  height: 50,
                  margin: EdgeInsets.only(top: 10.w),
                  decoration: BoxDecoration(
                      color: Color.fromRGBO(246, 246, 246, 1),
                      borderRadius: BorderRadius.circular(10.w)),
                  child: Row(
                    children: [
                      Expanded(
                        child: GestureDetector(
                            behavior: HitTestBehavior.translucent,
                            onTap: () async {
                              dynamic result =
                                  await Utils.showBottomSheetDialog(
                                      context,
                                      PasswordAuthDialog(
                                        title: 'Please confirm wallet password',
                                      ));
                              if (null != result &&
                                  result is String &&
                                  Utils.isNotEmpty(result)) {
                                setState(() {
                                  password2 = result;
                                });
                              }
                            },
                            child: Utils.isEmpty(password2)
                                ? Text(
                                    textMap['placeholder_2_label'],
                                    style: TextStyle(
                                        height: 20.w / 14.w,
                                        fontWeight: FontWeight.w400,
                                        fontSize: 14.sp,
                                        color:
                                            Color.fromRGBO(190, 189, 202, 1)),
                                  )
                                : GeneratePassword.generatePasswordWidget(
                                    password2, showPassword2)),
                      ),
                      Visibility(
                        visible: true,
                        child: GestureDetector(
                          onTap: () {
                            setState(() {
                              showPassword2 = !showPassword2;
                            });
                          },
                          child: (showPassword2
                              ? PublicImage(
                                  image:
                                      'assets/images/create_wallet/show_pass.png',
                                  width: 20.w,
                                  height: 20.w,
                                )
                              : PublicImage(
                                  image:
                                      'assets/images/create_wallet/hide_pass.png',
                                  width: 20.w,
                                  height: 20.w,
                                )),
                        ),
                      )
                    ],
                  ),
                ),
                if (showPassword2Warn.length > 0)
                  SizedBox(
                    height: 10.w,
                  ),
                Visibility(
                    visible: showPassword2Warn.length > 0,
                    child: ValidateTip(
                        text: showPassword2Warn,
                        margin: EdgeInsets.zero,
                        onClose: () {
                          setState(() {
                            showPassword2Warn = '';
                          });
                        })),
                if (textMap['needAgreement'])
                  Align(
                    alignment: Alignment.centerLeft,
                    child: Padding(
                      padding: EdgeInsets.only(top: 20.w),
                      child: Text(
                        textMap['input_label'],
                        style: TextStyle(
                            color: Color.fromRGBO(51, 51, 51, 1),
                            height: 20.w / 14.w,
                            fontSize: 14.sp,
                            fontWeight: FontWeight.w500),
                      ),
                    ),
                  ),
                if (textMap['needAgreement'])
                  Container(
                    margin: EdgeInsets.only(top: 10.w),
                    decoration: BoxDecoration(
                        color: Color.fromRGBO(246, 246, 246, 1),
                        borderRadius: BorderRadius.circular(10.w)),
                    child: TextField(
                      maxLength: 20,
                      maxLines: 1,
                      controller: textEditingController,
                      onChanged: (value) {
                        setState(() {
                          inputValue = value;
                        });
                      },
                      inputFormatters: [
                        FilteringTextInputFormatter.deny(RegExp(r'[^\w\s]+')),
                        // 禁止特殊字符
                        FilteringTextInputFormatter.deny(RegExp(r'\s')),
                        // 禁止空格
                      ],
                      focusNode: _focusNode,
                      onEditingComplete: () {
                        _focusNode.unfocus();
                      },
                      onTapOutside: (PointDownEvent) {
                        _focusNode.unfocus();
                      },
                      style: TextStyle(
                          fontSize: 14.sp,
                          fontWeight: FontWeight.w400,
                          color: Color.fromRGBO(51, 51, 51, 1)),
                      decoration: InputDecoration(
                          contentPadding: EdgeInsets.all(15.w),
                          hintStyle: TextStyle(fontSize: 14.sp),
                          counterText: '',
                          // 清空默认的字符计数器文本
                          hintText: inputValue,
                          border: InputBorder.none),
                    ),
                  ),
                if (Platform.isIOS)
                  Visibility(
                      visible: textMap['show_Biometric'],
                      child: Row(
                        children: [
                          Expanded(
                              child: Text(
                            'Activate Biometric Authentication',
                            style: TextStyle(
                                fontSize: 12.sp,
                                fontWeight: FontWeight.w400,
                                height: 17.w / 12.w,
                                color: Color.fromRGBO(51, 51, 51, 1)),
                          )),
                          Transform.scale(
                            scale: 0.6,
                            alignment: Alignment.centerRight,
                            child: Switch(
                              trackOutlineWidth:
                                  MaterialStateProperty.resolveWith(
                                      (states) => 0),
                              trackOutlineColor:
                                  MaterialStateProperty.resolveWith<Color>(
                                      (Set<MaterialState> states) {
                                if (states.contains(MaterialState.selected)) {
                                  return Colors.transparent; // 选中状态下的颜色
                                }
                                return Colors.transparent; // 默认颜色
                              }),
                              materialTapTargetSize:
                                  MaterialTapTargetSize.shrinkWrap,
                              activeColor: Colors.white,
                              activeTrackColor:
                                  Color.fromRGBO(246, 246, 246, 1),
                              trackColor:
                                  MaterialStateProperty.resolveWith<Color>(
                                      (Set<MaterialState> states) {
                                if (states.contains(MaterialState.selected)) {
                                  return Color.fromRGBO(
                                      134, 103, 254, 1); // 选中状态下的颜色
                                }
                                return Color.fromRGBO(246, 246, 246, 1); // 默认颜色
                              }),
                              inactiveTrackColor:
                                  Color.fromRGBO(246, 246, 246, 1),
                              thumbColor:
                                  MaterialStateProperty.resolveWith<Color>(
                                      (Set<MaterialState> states) {
                                if (states.contains(MaterialState.selected)) {
                                  return Colors.white; // 选中状态下的颜色
                                }
                                return Colors.white; // 默认颜色
                              }),
                              value: isBiometric,
                              onChanged: (value) async {
                                bool isCanCheckBiometric =
                                    await Authentication().canCheckBiometric();
                                if (!isCanCheckBiometric) {
                                  setState(() {
                                    isBiometric = false;
                                  });
                                  Toast.show(context,
                                      status: '0',
                                      message:
                                          'Enable device biometric authentication in system settings');
                                  return;
                                }
                                setState(() {
                                  isBiometric = value;
                                });
                              },
                            ),
                          )
                        ],
                      ))
              ],
            ),
          ),
        ),
        bottomNavigationBar: Container(
            width: double.infinity,
            height: textMap['needAgreement'] ? 125.w : 75.w,
            padding: EdgeInsets.only(bottom: 10.w),
            child: Column(
              children: [
                if (textMap['needAgreement'])
                  Expanded(
                    child: Container(
                      constraints: BoxConstraints.expand(),
                      padding: EdgeInsets.only(bottom: 11.w),
                      child: AgreementComp(
                        isCheck: isAgree,
                        name:
                            'I have read and agree Terms of Service and Privacy Agreement',
                        searchContent: [
                          'Terms of Service',
                          'Privacy Agreement'
                        ],
                        onSelect: (value) {
                          setState(() {
                            isAgree = value;
                          });
                        },
                        searchContentClick: (int index) {
                        },
                      ),
                    ),
                  ),
                PublicButton(
                    disabledStatus: !(password1.length > 0 &&
                        password2.length > 0 &&
                        inputValue.length > 0),
                    type: ButtonType.private,
                    text: textMap['btn_text'],
                    onClick: goingHome
                        ? null
                        : () {
                            _doConfirm();
                          })
              ],
            )) // bottomNavigationBar: Container(
        //   color: Colors.white,
        //   key: _containerKey,
        //   padding: EdgeInsets.only(bottom: 10),
        //   ,
        // ),
        );
  }
}
